<!--
 * @description: 剧本创作
 * @fileName: ScreenWriting
 * @author: 17076
 * @date: 2025/2/20-上午10:53
 * @version: V1.0.0
-->

<template>
  <div style="height: 100%; position: relative">
    <div class="center-segment">
      <el-segmented v-model="activeTabs" :options="tabsList" style="width: 440px" @change="() => { showConfirmPop = false }" />
    </div>
    <page-header :content="playData['playName']" @back="handleBack" @edit="handleEditPlayName">
      <div slot="right" class="flex-row right-buttons">
        <div v-if="activeTabs === '4'" class="view-change flex-row">
          <div :class="['view-list', mode === 'list' ? 'active' : '']" @click="handleChangeMode('list')">
            <svg-icon icon-class="list" />
          </div>
          <div :class="['view-picture', mode === 'grid' ? 'active' : '']" @click="handleChangeMode('grid')">
            <svg-icon icon-class="generate" />
          </div>
        </div>
        <div v-if="activeTabs === '4'" style="position: relative;cursor: pointer" @click="handleDirector">
          <svg-icon icon-class="director" />
          <el-badge :value="directorCount" :hidden="directorCount === 0" class="director-badge" />
        </div>
        <svg-icon v-if="activeTabs === '4'" icon-class="download" @click="handleDownloadLensFrame" />
        <div v-show="activeTabs === '1' && showNext1" class="liner-button" @click="handleRoles">下一步</div>
        <el-popover
          ref="confirmPop"
          v-model="showConfirmPop"
          placement="bottom-end"
          :visible-arrow="false"
          width="300"
          trigger="manual"
          popper-class="confirm-pop"
        >
          <confirm-pop :title="popTitle" cancel-text="再想想" @onCancel="() => { showConfirmPop = false }" @onConfirm="handleSaveStatus"/>
          <div v-show="activeTabs === '2' && showNext2" slot="reference" class="liner-button" @click="handleConfirmStoryboard">下一步</div>
        </el-popover>
        <div v-show="activeTabs === '3' && showNext3" class="liner-button" @click="handleBioscope">下一步</div>
<!--        <el-button v-if="activeTabs === '4'" class="liner-button" :disabled="Number(playData['createStatus']) >= 5" @click="handlePublish">保存并提交</el-button>-->
      </div>
    </page-header>
    <!--剧本-->
    <script-chapter v-if="activeTabs === '1' && currentPage === 1" :last-play-info="playData" @savePlay="handleSavePlayId" />
    <!--角色-->
    <character-design v-else-if="activeTabs === '2'" :play-id="playId.toString()" />
    <!--分镜内容-->
    <play-splitting v-else-if="activeTabs === '3'" :play-id="playId.toString()" />
    <!--分镜-->
    <creative-lens v-else :play-id="playId.toString()" />
    <!--角色设定弹窗-->
    <setting-role ref="role" @go="handleChangeTab" />
<!--    &lt;!&ndash;生成分镜&ndash;&gt;-->
<!--    <generate-storyboard ref="lens" @save="handleChangeTab" />-->
    <!--导演反馈-->
    <director-feedback ref="feedback" :play-id="playId.toString()" @update="handleSkipPage" />
    <!--剧本名称-->
    <edit-play-name ref="edit_play" @reload-data="queryPlayInfo" />
  </div>
</template>

<script>
import ScreenUpload from './script/ScreenUpload.vue'
import CharacterDesign from './roles/CharacterDesign.vue'
import PlaySplitting from './script/PlaySplitting.vue'
import SettingRole from './roles/SettingRole.vue'
import GenerateStoryboard from './lens/others/GenerateStoryboard.vue'
import CreativeLens from './lens/CreativeLens.vue'
import DirectorFeedback from '@/views/creativeCenter/playWriting/components/lens/others/DirectorFeedback.vue'
import ScriptChapter from '@/views/creativeCenter/playWriting/components/play/ScriptChapter.vue'
import { selectDetail, updatePlayDescInfo, downloadLensFrame, queryPlayShot } from '@/api/play'
import EditPlayName from '@/views/creativeCenter/playWriting/components/script/EditPlayName.vue'
import { mapActions, mapGetters } from 'vuex'
import { selectIsFinishedRole } from '@/api/roles'
import {saveLensFrameComment, selectComment} from '@/api/director'
import { queryLensList } from '@/api/lens'
import { downloadFile } from '@/utils/fileSave'
export default {
  name: 'ScreenWriting',
  components: {
    EditPlayName,
    ScriptChapter,
    DirectorFeedback,
    CreativeLens,
    GenerateStoryboard,
    SettingRole,
    PlaySplitting,
    CharacterDesign,
    ScreenUpload
  },
  data() {
    return {
      activeTabs: '1',
      tabsList: [
        { label: '剧本章节', value: '1', icon: 'play_tab' },
        { label: '角色设定', value: '2', icon: 'role_tab' },
        { label: '分镜内容', value: '3', icon: 'lens_tab' },
        { label: '分镜绘制', value: '4', icon: 'lens_tab' }
      ],
      // 剧本id
      playId: '',
      // 剧本数据
      playData: {},
      // 导演反馈数量
      directorCount: 0,
      // 当前页码
      currentPage: 1,
      // 显示确认弹窗
      showConfirmPop: false,
      // 确认弹窗标题
      popTitle: ''
    }
  },
  computed: {
    ...mapGetters({
      // 剧本章节是否显示下一步
      showNext1: 'lens/showNext1',
      // 角色设定是否显示下一步
      showNext2: 'lens/showNext2',
      // 分镜内容是否显示下一步
      showNext3: 'lens/showNext3',
      // 当前模式
      mode: 'lens/mode',
      // 剧本状态
      playStatus: 'lens/playStatus',
      // 选中分镜数据
      selectLens: 'lens/selectLens'
    })
  },
  mounted() {
    if (this.$route.query.id) {
      this.playId = this.$route.query.id
      this.queryPlayInfo()
      // 获取导演反馈列表
      this.queryDirectorFeedbackList()
    }
  },
  beforeDestroy() {
    // 清空缓存
    this.handleClearData()
  },
  methods: {
    ...mapActions({
      changeMode: 'lens/changeMode',
      changePlayStatus: 'lens/changePlayStatus',
      changePictureScale: 'lens/changePictureScale',
      changeCreateLens: 'lens/changeCreateLens',
      setSelectLens: 'lens/setSelectLens',
      changeDirectorSelectLensId: 'lens/changeDirectorSelectLensId',
      changePlayInfo: 'play/changePlayInfo'
    }),
    // 查询作品信息
    queryPlayInfo() {
      selectDetail({ id: this.$route.query.id }).then(res => {
        this.playData = res.data
        this.activeTabs = Number(res.data.createStatus) < 4 ? res.data.createStatus : '4'
        // 保存作品状态
        this.changePlayStatus(res.data['createStatus'])
        // 保存当前画面比例
        this.changePictureScale(res.data['pictureScale'])
        // 保存是否自动生成
        this.changeCreateLens(res.data['createLens'] || '0')
        // // 格式化tabs
        // this.tabsList.map(item => {
        //   this.$set(item, 'disabled', Number(item.value) > Number(res.data.createStatus))
        // })
      })
    },
    // 保存剧本id
    handleSavePlayId(id) {
      this.playId = id
    },
    // 设置分镜
    handleConfirmStoryboard() {
      // 判断是否存在角色未设置
      selectIsFinishedRole({ playId: this.playId }).then(res => {
        this.popTitle = res.data ? '剧本内容、角色设定完毕，点击【确定】继续当前操作。' : '角色信息尚未完善，继续操作可能影响分镜最终效果，点击【确定】继续当前操作'
        this.$nextTick(() => {
          this.showConfirmPop = true
          this.$refs.confirmPop.updatePopper()
        })
      })
    },
    // 保存状态
    handleSaveStatus() {
      this.showConfirmPop = false
      this.handleChangeTab('3')
      // 更新剧本状态
      updatePlayDescInfo({ id: this.playId, createStatus: '3' })
    },
    // 角色设定
    handleRoles() {
      // 判断是否存在剧本id
      if (this.$baseLodash.isEmpty(this.playId.toString())) {
        this.$baseMessage.error('请先上传剧本!')
        return
      }
      this.handleChangeTab('2')
      // this.$refs.role.show()
    },
    // 生成分镜
    handleBioscope() {
      // 判断是否加载完成
      queryPlayShot({ playId: this.playId }).then(res => {
        const loadingFinish = res.data.every(item => item['partShotStatus'] === false)
        if (!loadingFinish) {
          this.$baseMessage.error('分镜数据生成中,请耐心等待!')
          return
        }
        this.handleChangeTab('4')
        // this.$refs.lens.show({ id: this.playId })
      })
    },
    // 切换tab
    async handleChangeTab(val) {
      // 将tab 赋值
      this.activeTabs = val
      // 更新剧本状态
      await updatePlayDescInfo({ id: this.playId, createStatus: val })
      if (Number(val) > Number(this.playStatus)) {
        await this.changePlayStatus(val)
      }
      // // 同时手动将该tab 组件置为非禁用
      // this.tabsList.find(item => item.value === val).disabled = false
    },
    // 切换列表模式
    handleChangeMode(mode) {
      if (mode === 'grid' && !this.selectLens) {
        this.$baseMessage.error('请选择一条数据!')
        return
      }
      this.changeMode(mode)
    },
    // 发布
    handlePublish() {
      this.$baseConfirm('确定保存并提交吗? 确定后进入待审片状态', '提示', async() => {
        const { code, msg } = await updatePlayDescInfo({ id: this.playId, createStatus: '5' })
        code === 200 ? this.$baseMessage.success(msg || '提交成功!') : this.$baseMessage.error(msg || '提交失败!')
      })
    },
    // 导演反馈
    handleDirector() {
      this.$refs.feedback.show()
    },
    // 点击导演反馈某一条, 跳转到对应分镜
    handleSkipPage(data) {
      // 修改状态
      saveLensFrameComment({ ...data, id: data['lensFrameCommentId'], updStatus: '1' }).then(res => {
        if (res.code === 200) {
          this.queryDirectorFeedbackList()
        }
      })
      // 同时跳转界面
      queryLensList({ playId: this.playId }).then(res => {
        if (res.data && res.data.length > 0) {
          // 根据分镜id 查找对应分镜
          const lens = res.data.find(item => item.lensId === data.lensId)
          console.log('对应分镜数据', lens)
          // 保存对应分镜数据
          this.setSelectLens(lens)
          // 切换为grid 视图
          this.changeMode('grid')
          // 选中对应镜头
          this.changeDirectorSelectLensId(data['lensFrameId'])
        }
      })
    },
    // 下载剧本所有镜头图片
    handleDownloadLensFrame() {
      const _this = this
      this.$baseConfirm('确定要下载该剧本所有镜头图片吗?', '提示', async() => {
        const loading = _this.$baseLoading(-1, '文件导出中,请稍等..')
        const res = await downloadLensFrame({ playId: this.playId })
        await downloadFile(res, this.playData['playName'] + '.zip')
        loading.close()
      })
    },
    // 返回
    handleBack() {
      this.$router.back()
      setTimeout(() => {
        this.handleClearData()
      }, 500)
    },
    // 编辑剧本名称
    handleEditPlayName() {
      this.$refs.edit_play.show(this.playData)
    },
    // 获取导演反馈列表
    queryDirectorFeedbackList() {
      selectComment({ playId: this.playId, status: '0' }).then(res => {
        console.log(res, 7878)
        this.directorCount = res.data.length
      })
    },
    // 数据清空
    handleClearData() {
      // 清空画面比例
      this.changePictureScale('')
      // 清空选择的分镜
      this.setSelectLens(null)
      // 清空是否自动生成
      this.changeCreateLens('0')
      // 清空导演选择的分镜
      this.changeDirectorSelectLensId(null)
      // 清空当前模式
      this.changeMode('grid')
      // 清空剧本状态
      this.changePlayStatus('1')
      // 清空剧本数据
      this.changePlayInfo(null)
    }
  }
}
</script>

<style scoped lang="scss">
.center-segment {
  position: absolute;
  left: 50%;
  top: 10px;
  transform: translate(-50%, 0);
  z-index: 9;
}
.view-change {
  align-items: center;
  margin-right: 20px;
  >div {
    width: 55px;
    height: 35px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    cursor: pointer;
    border: 1px solid #B6C7D1;
    .svg-icon {
      margin: 0;
    }
  }
  .view-list {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    border-right: 0;
  }
  .view-picture {
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    border-left: 0;
  }
  .active {
    color: $base-color-default;
    border: 1px solid $base-color-default;
    .svg-icon {
      color: $base-color-default;
    }
  }
}
.right-buttons {
  align-items: center;
  .svg-icon {
    width: 1.5em;
    height: 1.5em;
    margin-right: 20px;
    color: #FFFFFF;
    cursor: pointer;
  }
  .director-badge {
    position: absolute;
    top: -8px;
    right: 5px;
  }
}
.header-title {
  color: #FFFFFF;
  border-left: 4px solid $base-color-default;
  padding-left: 10px;
}
::v-deep {
  .el-select {
    width: 100%;
  }
  .el-switch__label {
    color: #FFFFFF;
  }
}
</style>
